import axios, {
  InternalAxiosRequestConfig,
  RawAxiosResponseHeaders,
  AxiosResponseHeaders,
  AxiosRequestConfig,
} from 'axios'

import { ElMessage } from 'element-plus'
import { useUserStore } from '@/stores'

interface ResponseError {
  error: string
}

export interface AxiosResponse<T = any, D = any> {
  data: T
  status: number
  statusText: string
  headers: RawAxiosResponseHeaders | AxiosResponseHeaders
  config: AxiosRequestConfig<D>
  request?: any
}
// 创建 axios 实例
const request = axios.create({
  baseURL: 'http://localhost:3000/api',
  timeout: 20 * 1000,
  headers: { 'Access-Control-Allow-Origin': '*' },
  // withCredentials: true,
})

// 请求拦截器
request.interceptors.request.use(
  (config: InternalAxiosRequestConfig) => {
    const userStore = useUserStore()
    // 从pinia中获取token
    const token = userStore.token
    if (token) {
      // 请求时携带 token
      config.headers!.Authorization = token
    }
    return config
  },
  (error) => {
    const errorMsg = error?.message || 'Request Error'
    ElMessage({
      message: errorMsg,
      type: 'error',
    })
    return Promise.reject(error)
  }
)

// 响应拦截器
request.interceptors.response.use(
  (response: AxiosResponse) => {
    //接收到响应数据并成功后的一些共有的处理，关闭loading等
    const { data } = response
    return data
  },
  (error) => {
    const status = error.response?.status
    if (status !== 200) {
      const errorData: ResponseError = error.response?.data
      ElMessage.error(errorData.error)
    }
    // 处理http响应错误
    return Promise.reject(error.response?.data?.error)
  }
)

export default request
